<template>
  <h1>用户登录</h1>
  <form action="#">
    <div>
      <label for="username">用户名</label>
      <input type="text" id="username" v-model="form.username" />
    </div>
    <div>
      <label for="password">密码</label>
      <input type="text" id="password" v-model="form.password" />
    </div>
    <div>
      <button type="button" @click="login">登录/注册</button>
    </div>
  </form>
</template>

<script setup>
import { reactive } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const router = useRouter();
const store = useStore();
const form = reactive({
  username: "",
  password: "",
});

const login = async () => {
  try {
    console.log(form);
    const { data } = await axios.post("http://localhost:3000/api/login", form);
    if (data.user) {
      store.commit("setUser", data.user);
      router.push("/");
    }
  } catch (error) {
    console.log(error);
  }
};
</script>

<style scoped></style>
